package com.whynot.frame.ms.service.impl;

import com.whynot.frame.auth.jwt.token.JWTToken;
import com.whynot.frame.auth.jwt.utils.JWTUtil;
import com.whynot.frame.auth.shiro.cache.AuthCache;
import com.whynot.frame.basic.mybatis.service.BaseServiceImpl;
import com.whynot.frame.basic.util.DateUtil;
import com.whynot.frame.basic.util.StringUtils;
import com.whynot.frame.basic.util.WebUtil;
import com.whynot.frame.ms.entities.SysMenu;
import com.whynot.frame.ms.entities.SysRole;
import com.whynot.frame.ms.mapper.UserMapper;
import com.whynot.frame.ms.entities.SysUser;
import com.whynot.frame.ms.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 描    述:用户接口实现类
 * 创建时间: 2018/06/20
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper,SysUser> implements UserService {

    @Autowired
    AuthCache authCache;

    @Override
    public Map<String, Object> getUser(String userName) {
        SysUser param = new SysUser();
        param.setUserName(userName);
        try {
            return this.baseMapper.getUser(param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

    @Override
    public Set<String> findRolesByUser(String userId) {
        List<SysRole> roles = this.baseMapper.findRolesByUser(userId);
        Set<String> set = new HashSet<String>();
        for (SysRole sysRole:roles
             ) {
            set.add(sysRole.getRoleKey());
        }
        return set;
    }

    @Override
    public Set<String> findPermissionsByUser(String userId) {
        List<SysMenu> menus = this.baseMapper.findPermissionsByUser(userId);
        Set<String> set = new HashSet<String>();
        for (SysMenu sysMenu:menus
                ) {
            set.add(sysMenu.getPermissionKey());
        }
        return set;
    }

    @Override
    public String login(String userName, String pwd) throws Exception {
        Map<String, Object> map = getUser(userName);
        if(StringUtils.isEmpty(map)){
            throw new UnknownAccountException("账号不存在");
        }
        SysUser param = new SysUser();
        param.setPwd(pwd);
        param.setUserName(userName);
        SysUser sysUser = this.baseMapper.login(param);
        if(StringUtils.isEmpty(sysUser)){
            throw new InterruptedException("账号,密码不匹配");
        }

        if(StringUtils.isEmpty(sysUser.getEnabled()) || sysUser.getEnabled() != 1){
            throw new DisabledAccountException("账号被停用");
        }

        String authorization = "";
        if(sysUser.getPwd().equals(pwd)){
            authorization = JWTUtil.sign(userName, pwd);
            Subject curUser = SecurityUtils.getSubject();
            JWTToken token = new JWTToken(authorization);
            curUser.login(token);
            authCache.setUser(map);
        }
        return authorization;

    }

    @Override
    public Boolean updatePwd(String oldPwd, String newPwd) {
       Map map = (Map)SecurityUtils.getSubject();
       String pwd = map.get("password").toString();
       String userName = map.get("usernmae").toString();
       if(pwd.equals(oldPwd)){
           return false;
       }
       return this.baseMapper.updatePwd(userName,newPwd);
    }

    @Override
    public List<SysRole> findRolesByUserId() {
        String userId = WebUtil.gwtUserId();
        if(StringUtils.isEmpty(userId)){
            return null;
        }
        return this.baseMapper.findRolesByUser(userId);
    }

    @Override
    public List<SysMenu> findPermissionsByUserId() {
        String userId = WebUtil.gwtUserId();
        if(StringUtils.isEmpty(userId)){
            return null;
        }
        return this.baseMapper.findPermissionsByUser(userId);
    }

    @Override
    public int insertUserRole(String userId,String roleIds) {
        List<Map> list = new ArrayList<Map>();
        String[] arr = roleIds.split(",");
        for (String str:
             arr) {
                Map map = new HashMap();
                map.put("userId",userId);
                map.put("roleId",str);
                list.add(map);
        }
        return this.baseMapper.insertUserRole(list);
    }

    public String test() throws InterruptedException {
        Thread.sleep(6000);
        return "";
    }

    @Transactional
    public void insertTest() throws InterruptedException {
       // Thread.sleep(6000);

        SysUser sysUser = new SysUser();
        sysUser.setUserName("cesss");
        sysUser.setPwd("344");
        sysUser.setCreator("aaa");
        sysUser.setCreateTime(DateUtil.getTime());
        this.baseMapper.insert(sysUser);
        int i = 1/0;
    }

    /*
     * 清除缓存信息
     * **/
   /* private Boolean isExistAuthorizationInfo(){
        Subject subject = SecurityUtils.getSubject();
        subject.isAuthenticated();
        RealmSecurityManager realmSecurityManager =
                (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyRealm realm = (MyRealm) realmSecurityManager.getRealms().iterator().next();
        realm.
    }*/
}